﻿using Newtonsoft.Json;
using System;

namespace RM.BasicLibrary.Exceptions
{
    public class CodeInfo
    {
        public string MethodName { get; set; }
        public int Row { get; set; }
        public string Msg { get; set; }
        public Exception Exception { get; set; }
        public Type Class { get; set; }
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }
        /// <summary>
        /// 重写后的字符串 $"Class:{DeclaringType} MethodName:{MethodName} Row:{Row} Message:{Message} Exception:{Exception}";
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return $"Class:{Class} MethodName:{MethodName} Row:{Row} Message:{Msg} Exception:{Exception}";
        }
        /// <summary>
        /// skipFrames:
        ///     从其开始跟踪堆栈中向上传递的帧数。
        ///
        ///   fNeedFileInfo:
        ///     true 若要捕获文件名、 行号和列号;否则为 false。
        /// </summary>
        /// <param name="skipFrames"></param>
        /// <param name="fNeedFileInfo"></param>
        /// <param name="messge"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public CodeInfo GetCodeInfo(int skipFrames = 0, bool fNeedFileInfo = true, string messge = "", Exception exception = null)
        {
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(skipFrames, fNeedFileInfo);
            MethodName = st.GetFrame(0).GetMethod().Name;
            Class = st.GetFrame(0).GetMethod().DeclaringType;
            Row = st.GetFrame(0).GetFileLineNumber();
            Msg = messge;
            //Exception = exception;
            return this;
        }
        /// <summary>
        /// skipFrames:
        ///     从其开始跟踪堆栈中向上传递的帧数。
        ///
        ///   fNeedFileInfo:
        ///     true 若要捕获文件名、 行号和列号;否则为 false。
        ///  /// </summary>
        /// <param name="skipFrames"></param>
        /// <param name="fNeedFileInfo"></param>
        /// <param name="messge"></param>
        /// <returns></returns>
        public CodeInfo GetCodeInfo(int skipFrames = 0, bool fNeedFileInfo = true, string messge = "")
        {
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(skipFrames, fNeedFileInfo);
            MethodName = st.GetFrame(0).GetMethod().Name;
            Class = st.GetFrame(0).GetMethod().DeclaringType;
            Row = st.GetFrame(0).GetFileLineNumber();
            Msg = messge;
            return this;
        }
    }
}
